package com.nixsolutions.validator;

import com.nixsolutions.dao.UserDao;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.nixsolutions.form.UserForm;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author yakimovich
 */
@Component
public class UserFormValidator implements Validator {

    @Override
    public boolean supports(Class<?> aClass) {
        return UserForm.class.isAssignableFrom(aClass);
    }

    @Autowired
    private UserDao userDao;

    @Override
    public void validate(Object target, Errors errors) {
        UserForm userForm = (UserForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "login.empty", "Login must not be empty.");
        String login = userForm.getLogin();

        if (userDao.findByLogin(login) != null){
            errors.rejectValue("login", "login.exist", "User with such login already exist.");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.empty", "Password must not be empty.");
        if (!(userForm.getPassword()).equals(userForm.getPasswordConfirm())) {
            errors.rejectValue("confirmPassword", "confirmPassword.passwordDontMatch", "Passwords don't match.");
        }

        if (!EmailValidator.getInstance().isValid(userForm.getEmail())) {
            errors.rejectValue("email", "email.notValid", "Email address is not valid.");
        }
    }
}
